package org.goldfish.message_board01.servlets;

import jakarta.servlet.http.HttpSession;
import org.goldfish.message_board01.services.MessageService;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AddMessageServlet extends GFAbstractServlet {

    private final MessageService messageService = new MessageService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("addMessage.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false); // Retrieve session
        if (session == null || session.getAttribute("username") == null) {
            // Redirect to login page if session or username is missing
            response.sendRedirect("login");
            return;
        }

        String sender = (String) session.getAttribute("username");
        String title = request.getParameter("title");
        String content = request.getAttribute("content").toString();

        if (title == null || title.isEmpty() || content == null || content.isEmpty()) {
            response.sendRedirect("addMessage?error=Title and content cannot be empty");
            return;
        }

        boolean success = messageService.addMessage(sender, title, content);
        if (success) {
            response.sendRedirect("messages");
        } else {
            response.sendRedirect("addMessage?error=Unable to add message");
        }
    }

}
